#include "widget.h"
#include "ui_widget.h"
#include <QBitmap>
#include <QPixmap>
#include <QPainter>
#include <sleep_widget.h>
#include <QEventLoop>
#include <QMessageBox>
#include <QCloseEvent>
#include <work_tip.h>
#include <QMouseEvent>
#include <QDesktopWidget>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    setMask(QBitmap(QPixmap(":/pic/tomato.png").mask()));
    QPalette pal = palette();
    pal.setColor(QPalette::Background, QColor(0x00,0xff,0x00,0x00));
    setPalette(pal);
    work_time=WORK_TIME;
    work_timer.start(1000);
    connect(&work_timer,SIGNAL(timeout()),this,SLOT(on_work_timer()));
    icon.setIcon(QIcon(":/pic/tomato.png"));
    menu.addAction("关于",this,SLOT(on_about()));
    menu.addAction("暂停计时",this,SLOT(on_pause()));
    menu.addAction("继续计时",this,SLOT(on_resume()));
    menu.addAction("重新计时",this,SLOT(on_reset()));
    menu.addAction("开始休息",this,SLOT(on_sleep()));

    menu.addAction("关闭",this,SLOT(on_exit()));
    icon.setContextMenu(&menu);
    icon.show();
    move(QApplication::desktop()->width()-200,100);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::paintEvent(QPaintEvent *){
    QPainter painter(this);
    painter.drawPixmap(0,0,QPixmap(":/pic/tomato.png"));
}

void Widget::on_work_timer(){
    QString str=[](int t){
        return QString("%1").arg(t/60,2,10,QLatin1Char('0'))+":"+QString("%1").arg(t%60,2,10,QLatin1Char('0'));
    }(--work_time<0?0:work_time);
    ui->msg_lab->setText(str);
    if(work_time==60){
        icon.showMessage("温馨提示","还有1分钟将进入休息模式，请您做好准备 ^_^");
    }
    if(work_time<=0){
        work_timer.stop();
        Sleep_Widget *slp=new Sleep_Widget;
        slp->showFullScreen();
        QEventLoop loop;
        connect(slp,SIGNAL(about_close()),&loop,SLOT(quit()));
        loop.exec();
        slp->deleteLater();
        Work_Tip tip(this);
        tip.exec();
        work_time=WORK_TIME;
        work_timer.start(1000);
    }
}

void Widget::on_about(){
    QMessageBox msgbox(this);
    msgbox.setIconPixmap(QPixmap(":/pic/sponse.png"));
    msgbox.setText("版本："+version+"\n作者：SkyFire\nQQ：1513008876\nE-mail：skyfireitdiy@hotmail.com\n\n\n<---支付宝扫描左侧二维码赞助作者^_^");
    msgbox.exec();
}

void Widget::on_exit(){
    real_close=true;
    close();
}

void Widget::closeEvent(QCloseEvent *event){
    if(!real_close)
        event->ignore();
    else
        QApplication::exit(0);
}

void Widget::mousePressEvent(QMouseEvent *event){
    if(event->button()==Qt::RightButton){
        menu.popup(cursor().pos());
    }
}

void Widget::on_pause(){
    if(work_timer.isActive())
        work_timer.stop();
}

void Widget::on_resume(){
    if(!work_timer.isActive())
        work_timer.start(1000);
}

void Widget::on_reset(){
    work_time=WORK_TIME;
    if(!work_timer.isActive())
        work_timer.start(1000);
}

void Widget::on_sleep(){
    work_time=0;
    if(!work_timer.isActive())
        work_timer.start(1000);
}
